﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using DotNetWikiBot;
using System.Threading;

namespace AlexTranslator
{
    public class WikiWinForm : Form
    {
        Site ukSite;

        object syncObj = new object();

        public WikiWinForm()
        {
            /*
            ((Action)delegate
            {
                Site s = RuSite;
            }).BeginInvoke(null, null);
            */

            ((Action)delegate
            {
                Site s = UkSite;
            }).BeginInvoke(null, null);
        }

        public void OpenPage(string pageToOpen)
        {
            //Page page = new Page(UkSite, txbDstPage.Text);

            System.Diagnostics.Process.Start(UkSite.site + @"/wiki/" + pageToOpen);
        }
        //ThreadStart   
            
        public  Site UkSite
        {
            get
            {
                if (ukSite == null && !DesignMode)
                {
                    lock (syncObj)
                    {
                        
                        ukSite = LoginToSite("http://uk.wikipedia.org");
                    }
                    return ukSite;
                }
                    
                else
                    return ukSite;
            }
            set { ukSite = value; }
        }

        private Site ruSite;

        public Site RuSite
        {

            get
            {
                if (ruSite == null && !DesignMode)
                    return ruSite = LoginToSite("http://ru.wikipedia.org");
                else
                    return ruSite;
            }
            set { ruSite = value; }
        }

        public static Site LoginToSite(string site)
        {

            string userName;
            string userPass;
            string filename = "Login.dat";
            if (File.Exists("Cache" + Path.DirectorySeparatorChar + filename) == true)
            {
                string[] lines = File.ReadAllLines(
                    "Cache" + Path.DirectorySeparatorChar + filename, Encoding.UTF8);
                if (lines.Length >= 2)
                {
                    //this.site = lines[0];
                    userName = lines[0];
                    userPass = lines[1];

                }
                else
                    throw new WikiBotException(
                        Bot.Msg("\"\\Cache\\Login.dat\" file is invalid."));
            }
            else
                throw new WikiBotException(Bot.Msg("\"\\Cache\\Login.dat\" file not found."));

            Site result = new Site(site, userName, userPass);

            return result;
        }  
    }
}
